<template>
  <div class="commodity-container">
    <el-card class="commodity-card">
      <template #header>
        <div class="card-header">
          <span>商品列表</span>
          <div class="header-actions">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入商品名称"
              style="width: 300px; margin-right: 10px"
              clearable
              @clear="searchCommodities"
              @keyup.enter="searchCommodities"
            >
              <template #append>
                <el-button icon="Search" @click="searchCommodities">搜索</el-button>
              </template>
            </el-input>
            <el-button type="primary" icon="Plus" @click="handleAddCommodity">新增商品</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="commodityList"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="商品ID" width="80" />
        <el-table-column prop="productName" label="产品名称" width="150" />
        <el-table-column prop="merchantId" label="所属商户" width="120" />
        <el-table-column prop="productCategoryId" label="产品种类" width="120" />
        <el-table-column prop="productDescription" label="产品描述" width="150" />
        <el-table-column prop="productPrice" label="产品价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.productPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="productStatus" label="产品状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.productStatus === 1" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              :type="scope.row.productStatus === 1 ? 'danger' : 'success'"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.productStatus === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 商品编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="commodityFormRef"
        :model="commodityForm"
        :rules="commodityFormRules"
        label-width="100px"
      >
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="commodityForm.productName" />
        </el-form-item>
        <el-form-item label="所属商户" prop="merchantId">
          <el-input v-model="commodityForm.merchantId" />
        </el-form-item>
        <el-form-item label="产品种类" prop="productCategoryId">
          <el-input v-model="commodityForm.productCategoryId" />
        </el-form-item>
        <el-form-item label="产品描述" prop="productDescription">
          <el-input v-model="commodityForm.productDescription" type="textarea" />
        </el-form-item>
        <el-form-item label="产品价格" prop="productPrice">
          <el-input-number v-model="commodityForm.productPrice" :min="0" :step="0.01" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="产品状态" prop="productStatus">
          <el-switch
            v-model="commodityForm.productStatus"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCommodityForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useProductStore } from '@/stores/product'
import { storeToRefs } from 'pinia'

const productStore = useProductStore()
const { products: commodityList, loading } = storeToRefs(productStore)

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')

// 商品表单
const commodityFormRef = ref()
const commodityForm = reactive({
  id: null,
  productName: '',
  merchantId: '',
  productCategoryId: '',
  productDescription: '',
  productPrice: 0,
  productStatus: 1
})

// 表单验证规则
const commodityFormRules = {
  productName: [
    { required: true, message: '请输入产品名称', trigger: 'blur' }
  ],
  merchantId: [
    { required: true, message: '请输入所属商户', trigger: 'blur' }
  ],
  productCategoryId: [
    { required: true, message: '请输入产品种类', trigger: 'blur' }
  ],
  productDescription: [
    { required: true, message: '请输入产品描述', trigger: 'blur' }
  ],
  productPrice: [
    { required: true, message: '请输入产品价格', trigger: 'blur' }
  ]
}

// 搜索商品
const searchCommodities = async () => {
  if (searchForm.keyword) {
    await productStore.searchProductsByName(searchForm.keyword)
  } else {
    await productStore.fetchProducts()
  }
  pagination.total = commodityList.value.length
}

// 新增商品
const handleAddCommodity = () => {
  dialogTitle.value = '新增商品'
  dialogVisible.value = true
  // 重置表单
  Object.assign(commodityForm, {
    id: null,
    productName: '',
    merchantId: '',
    productCategoryId: '',
    productDescription: '',
    productPrice: 0,
    productStatus: 1
  })
}

// 编辑商品
const handleEdit = (row) => {
  dialogTitle.value = '编辑商品'
  dialogVisible.value = true
  // 填充表单数据
  Object.assign(commodityForm, {
    id: row.id,
    productName: row.productName,
    merchantId: row.merchantId,
    productCategoryId: row.productCategoryId,
    productDescription: row.productDescription,
    productPrice: row.productPrice,
    productStatus: row.productStatus
  })
}

// 提交商品表单
const submitCommodityForm = () => {
  commodityFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let result
        if (commodityForm.id) {
          // 编辑商品
          result = await productStore.updateProduct(commodityForm.id, {
            productName: commodityForm.productName,
            merchantId: commodityForm.merchantId,
            productCategoryId: commodityForm.productCategoryId,
            productDescription: commodityForm.productDescription,
            productPrice: commodityForm.productPrice,
            productStatus: commodityForm.productStatus
          })
        } else {
          // 新增商品
          result = await productStore.addProduct({
            productName: commodityForm.productName,
            merchantId: commodityForm.merchantId,
            productCategoryId: commodityForm.productCategoryId,
            productDescription: commodityForm.productDescription,
            productPrice: commodityForm.productPrice,
            productStatus: commodityForm.productStatus
          })
        }
        
        if (result.success) {
          ElMessage.success(commodityForm.id ? '编辑成功' : '新增成功')
          dialogVisible.value = false
        }
      } catch (error) {
        ElMessage.error(error.message || (commodityForm.id ? '编辑失败' : '新增失败'))
      }
    }
  })
}

// 关闭对话框
const handleDialogClose = () => {
  commodityFormRef.value.resetFields()
}

// 改变商品状态
const handleStatusChange = async (row) => {
  const action = row.productStatus === 1 ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(`确定要${action}产品"${row.productName}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const result = await productStore.toggleProductStatus(row.id)
    if (result.success) {
      ElMessage.success(`${action}成功`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '状态切换失败')
    }
  }
}

// 删除商品
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除产品"${row.productName}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const result = await productStore.deleteProduct(row.id)
    if (result.success) {
      ElMessage.success('删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 分页相关方法
const handleSizeChange = (val) => {
  pagination.pageSize = val
  ElMessage.info(`每页显示 ${val} 条`)
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  ElMessage.info(`当前页: ${val}`)
}

// 页面加载时获取数据
onMounted(async () => {
  await productStore.fetchProducts()
  pagination.total = commodityList.value.length
  ElMessage.success('商品列表页面加载完成')
})
</script>

<style scoped>
.commodity-container {
  padding: 20px;
  background-color: #f0f2f5;
  height: 100%;
  box-sizing: border-box;
}

.commodity-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>